<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge,chrome=1">
    <meta name="referrer" content="never">
    <title>bind</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        ul {
            list-style: none;
        }
    </style>
</head>
<body>
    
    <script type="text/javascript">
        /* 
        fn.bind(thisObj, [一个或多个参数])
            返回一个新函数，新函数中的this为第一个接受的参数对象，其余与原函数一致
            如果有参数，则固定参数，用于制作偏函数

            偏函数：固定了一部分参数的函数

            bind方法称为夺取函数
        */

        var uname = "window";

        var user = {
            uname: "李白"
        }

        function sayName(){
            console.log(this.uname);
        }

        var returnValue = sayName.bind(user);
        // console.log(returnValue);

        window.returnValue(); // 李白

        console.clear();

        function sing(status, lyric){
            console.log(this.uname + " " + status + " sing: " + lyric);
        }

        var rv = sing.bind(user, "开心的");

        rv("伤心太平洋...");
        rv("难过太平洋...");
        rv("忧愁太平洋...");

        console.clear();

        function say(time, word){
            console.log(`[${time}] ${this.uname} said: ${word}`);
        }

        var date = new Date();
        var sameTime = say.bind(user, date.getHours() + ":" + date.getMinutes());
        sameTime("hello");
        sameTime("world");
        sameTime("me too");


        function makeBind(func, ...args){
            return func.bind(this, ...args); // this => window
            // return function(){
            //     // this -> 接受的对象
            //     return func.apply(this, args);
            // }
        }

        user.sayTwo = makeBind(say, date.getHours() + ":" + date.getMinutes(), "nice to meet you");
        user.sayTwo();
    </script>
</body>
</html>